﻿using System;
using System.Threading;
using System.Drawing;
using System.Diagnostics;

namespace Utility
{
    public class GameMonitor
    {
        public bool IsGameRunning
        {
            get => isGameRunning;
            set
            {
                if (value != isGameRunning)
                {
                    if (value)
                    {
                        StartGameMode();
                        Debug.Print("game mode start");
                    }
                    else
                    {
                        EndGameMode();
                        Debug.Print("game mode end");
                    }
                    isGameRunning = value;
                }
            }
        }

        private bool isGameRunning = false;

        public event Action StartGameMode;

        public event Action EndGameMode;

        private Rectangle fullscreen = Common.GetFullscreen();

        private IntPtr workerWHandle;

        public GameMonitor(Action start, Action end)
        {
            StartGameMode += start;
            EndGameMode += end;
            FindWorkerW();
            new Thread(() =>
            {
                while (true)
                {
                    IsGameRunning = IsGameRunningNow();
                    Thread.Sleep(1000);
                }
            })
            {
                IsBackground = true
            }.Start();
        }

        private bool IsGameRunningNow()
        {
            IntPtr foregroundWindow = WinAPI.GetForegroundWindow();
            if (foregroundWindow == workerWHandle)
            {
                return false;
            }
            WinAPI.GetWindowRect(foregroundWindow, out Rectangle windowRect);
            Debug.Print(foregroundWindow.ToString() + "\t" + windowRect.ToString());
            if (windowRect == fullscreen)
            {
                return !Convert.ToBoolean(WinAPI.GetWindowLong(foregroundWindow, WinAPI.WindowLongFlags.GWL_STYLE) & Convert.ToInt32(WinAPI.WindowStyles.WS_CAPTION));
            }
            return false;
        }

        private void FindWorkerW()
        {
            WinAPI.EnumWindows(((topHandle, _) =>
            {
                if (WinAPI.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", string.Empty) != IntPtr.Zero)
                {
                    workerWHandle = topHandle;
                    return false;
                }
                return true;
            }), IntPtr.Zero);
        }
    }
}
